package com.chatplus.application.service.draw.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.common.page.PageParam;
import com.chatplus.application.dao.draw.SdJobDao;
import com.chatplus.application.domain.entity.draw.SdJobEntity;
import com.chatplus.application.service.draw.SdJobService;
import org.springframework.stereotype.Service;

/**
 * Stable Diffusion 任务表业务逻辑实现
 *
 * <p>Table: t_sd_job - Stable Diffusion 任务表</p>
 *
 * @author developer
 * @see SdJobEntity
 */
@Service
public class SdJobServiceImpl extends ServiceImpl<SdJobDao, SdJobEntity> implements SdJobService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(SdJobServiceImpl.class);

    @Override
    public Page<SdJobEntity> getSdJobPage(PageParam pageParam, Boolean finish, Long userId, Boolean publish) {
        LambdaQueryWrapper<SdJobEntity> wrapper = new LambdaQueryWrapper<SdJobEntity>()
                .eq(userId != null, SdJobEntity::getUserId, userId)
                .eq(publish != null, SdJobEntity::getPublish, Boolean.TRUE.equals(publish) ? 1 : 0)
                .orderByDesc(SdJobEntity::getCreatedAt);
        if (finish != null) {
            if (Boolean.TRUE.equals(finish)) {
                wrapper.eq(SdJobEntity::getProgress, 100);
                wrapper.isNotNull(SdJobEntity::getImgUrl);
            } else {
                wrapper.ne(SdJobEntity::getProgress, -1);
                wrapper.lt(SdJobEntity::getProgress, 100);
            }
        }
        return baseMapper.selectPage(pageParam.toPage(), wrapper);
    }

    @Override
    public long getRunningJobCount(Long userId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<SdJobEntity>()
                .eq(SdJobEntity::getUserId, userId)
                .ne(SdJobEntity::getProgress, -1)
                .lt(SdJobEntity::getProgress, 100));
    }
}
